package com.yenlien.traceyun.control.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.control.dao.LevelSecondDao;
import com.yenlien.traceyun.control.dao.LevelTopDao;
import com.yenlien.traceyun.control.dao.ScienceInfoDao;
import com.yenlien.traceyun.control.entity.LevelSecond;
import com.yenlien.traceyun.control.entity.LevelTop;
import com.yenlien.traceyun.control.entity.ScienceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.beans.Transient;
import java.util.*;

/**
 * 科技服务信息
 */
@Service
public class ScienceInfoService {

    @Autowired
    private ScienceInfoDao scienceInfoDao;

    @Autowired
    private LevelSecondDao levelSecondDao;

    @Autowired
    private LevelTopDao levelTopDao;


    public Page<ScienceInfo> findByList(final ScienceInfo scienceInfo) {
        Pageable pageable = PageRequest.of(scienceInfo.getPage(), scienceInfo.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<ScienceInfo> all = scienceInfoDao.findAll(new Specification<ScienceInfo>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<ScienceInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
//                if (!StringUtils.isEmpty(scienceInfo.getTitleName())) {
//                    list.add(cb.equal(root.get("titleName"), scienceInfo.getTitleName()));        //根据传的状态筛选
//                }
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        }, pageable);
        List<ScienceInfo> li = new ArrayList<>();
        List<ScienceInfo> content = all.getContent();
        for (ScienceInfo info : content) {
            LevelSecond second = levelSecondDao.findById(info.getSecondId());
            if (second != null) {
                LevelTop top = levelTopDao.findById(second.getTopId());
                info.setSecondName(second.getName());
                info.setTopId(second.getTopId());
                info.setTopName(top.getName());
                li.add(info);
            }
        }
        Page<ScienceInfo> pageImpianto = new PageImpl<ScienceInfo>(li, pageable, all.getTotalElements());
        return pageImpianto;
    }

    /**
     * 自定义分页查询加条件,只携带一级分类
     */
    public Page<ScienceInfo> findByPage(final ScienceInfo scienceInfo) {
        List<ScienceInfo> list = new ArrayList<>();
        List<Map<String, Object>> li = scienceInfoDao.findByPageAble(scienceInfo.getTopId(), scienceInfo.getPage(), scienceInfo.getPageSize());
        int total = 0;
        for (Map<String, Object> map : li) {
            ScienceInfo info = new ScienceInfo();

            info.setId(map.get("id").toString());
            info.setTitleName(map.get("title_name").toString());
            info.setContent(map.get("content").toString());
            info.setCreateTime((Date) map.get("create_time"));
            info.setTopId(map.get("top_id").toString());
            info.setTopName(map.get("topName").toString());
            info.setSecondId(map.get("second_id").toString());
            info.setSecondName(map.get("secondName").toString());
            total = Integer.valueOf(map.get("total").toString());
            list.add(info);
        }
        Pageable pageable = PageRequest.of(scienceInfo.getPage(), scienceInfo.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<ScienceInfo> pipelinePage = new PageImpl<>(list, pageable, total);
        return pipelinePage;
    }

    /**
     * 自定义分页查询加条件,携带一级分类加二级分类
     */
    public Page<ScienceInfo> findByPageSecond(final ScienceInfo scienceInfo) {
        List<ScienceInfo> list = new ArrayList<>();
        List<Map<String, Object>> li = scienceInfoDao.findByPageAble2(scienceInfo.getTopId(), scienceInfo.getSecondId(), scienceInfo.getPage(), scienceInfo.getPageSize());
        int total = 0;
        for (Map<String, Object> map : li) {
            ScienceInfo info = new ScienceInfo();

            info.setId(map.get("id").toString());
            info.setTitleName(map.get("title_name").toString());
            info.setContent(map.get("content").toString());
            info.setCreateTime((Date) map.get("create_time"));
            info.setTopId(map.get("top_id").toString());
            info.setTopName(map.get("topName").toString());
            info.setSecondId(map.get("second_id").toString());
            info.setSecondName(map.get("secondName").toString());
            total = Integer.valueOf(map.get("total").toString());
            list.add(info);
        }
        Pageable pageable = PageRequest.of(scienceInfo.getPage(), scienceInfo.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<ScienceInfo> pipelinePage = new PageImpl<>(list, pageable, total);
        return pipelinePage;
    }

    /**
     * 添加，编辑
     */
    @Transient
    public Object save(ScienceInfo scienceInfo) {
        if (!StringUtils.isEmpty(scienceInfo.getId())) {
            scienceInfoDao.delete(scienceInfo);
        }
        return scienceInfoDao.save(scienceInfo);
    }

    /**
     * 根据id查询
     */
    public Object findById(String id) {
        List<Map<String, Object>> li = scienceInfoDao.findById(id);
        if (li.size() == 0) {
            li = scienceInfoDao.findByTopId(id);
        }
        return li;
    }

    /**
     * 删除
     */
    @Transient
    public void deleteById(String id) {
        scienceInfoDao.deleteById(id);
    }

    /**
     * 获取所有数据
     */
    public JSONArray treeList() {
        JSONArray tree = new JSONArray();
        List<LevelTop> all = levelTopDao.findAll();
        for (LevelTop levelTop : all) {
            JSONObject topList = new JSONObject();
            List<LevelSecond> li = levelSecondDao.findByTopId(levelTop.getId());
            JSONArray secondList = JSONArray.parseArray(JSON.toJSONString(li));

            topList.put("name", levelTop.getName());
            topList.put("id", levelTop.getId());
            tree.add(topList);
            if (li.size() > 0) {
                for (LevelSecond levelSecond : li) {
                    JSONObject allInfo = new JSONObject();
                    List<ScienceInfo> allList = scienceInfoDao.findBySecondId(levelSecond.getId());
                    allInfo.put("name", levelSecond.getName());
                    allInfo.put("id", levelSecond.getId());
                    allInfo.put("create_time", levelSecond.getCreateTime());
                    allInfo.put("info", allList);
                    secondList.add(allInfo);
                }
            } else {
                JSONObject allInfo = new JSONObject();
                List<ScienceInfo> allList = scienceInfoDao.findBySecondId(levelTop.getId());
                allInfo.put("info", allList);
                secondList.add(allInfo);
            }
            topList.put("secondList", secondList);

        }
        return tree;
    }

    /**
     * 获取列表分类数据
     */
    public JSONArray getTree() {
        JSONArray tree = new JSONArray();
        List<LevelTop> all = levelTopDao.findAll();
        for (LevelTop levelTop : all) {
            JSONObject topList = new JSONObject();
            List<LevelSecond> li = levelSecondDao.findByTopId(levelTop.getId());
            topList.put("name", levelTop.getName());
            topList.put("id", levelTop.getId());
            topList.put("secondList", li);
            tree.add(topList);
        }
        return tree;
    }

    /**
     * 添加分类,编辑分类
     */
    @Transactional
    public Object saveLevel(JSONObject param) {
        LevelTop topLevel = levelTopDao.finbyName(param.getString("name"));

        LevelTop levelTop = new LevelTop();
        levelTop.setName(param.getString("name"));
        levelTop.setCreateTime(new Date());
        try {
            if (topLevel != null) {         //名字重复不保存
                levelTop.setId(topLevel.getId());
            }
            topLevel = levelTopDao.save(levelTop);
            List<LevelSecond> list = new ArrayList<>();
            JSONArray array = param.getJSONArray("levelSecond");
            for (int i = 0; i < array.size(); i++) {
                LevelSecond levelSecond = new LevelSecond();

                levelSecond.setCreateTime(new Date());
                levelSecond.setName(array.getString(i));
                levelSecond.setTopId(topLevel.getId());
                LevelSecond secondLevel = levelSecondDao.findBySecondName(array.getString(i));
                if (secondLevel != null) {
                    levelSecond.setId(secondLevel.getId());
                }
                list.add(levelSecond);
            }
            return levelSecondDao.saveAll(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
